package org.jimmy.tang.beannameaware;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.BeanNameAware;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;

/**
 * @author jimmy
 * 
 */
public class SimpleBean implements InitializingBean, DisposableBean,
        BeanNameAware, BeanFactoryAware, Runnable {

    private ConfigurableListableBeanFactory configurableListableBeanFactory;

    @Override
    public void setBeanName(String beanName) {
        System.out.println("this is info from BeanNameAware and beanName is:"
                + beanName);

    }

    @Override
    public void setBeanFactory(BeanFactory factory) throws BeansException {
        // 自动注册成线程
        if (factory instanceof ConfigurableListableBeanFactory) {
            System.out.println("this is info from BeanNameAware and beanName");
            configurableListableBeanFactory = (ConfigurableListableBeanFactory) factory;
            Runtime.getRuntime().addShutdownHook(new Thread(this));
        }

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        System.out
                .println("this is info from afterpropertiesSet from SimpleBean");
    }

    @Override
    public void run() {
        // 线程调用destroySingletons
        configurableListableBeanFactory.destroySingletons();

    }

    private String name;
    private String sex;
    private String age;

    public void destroyMethod() {
        System.out.println("this is info from customer destroy method");
    }

    @Override
    public void destroy() {
        System.out.println("this is info from destroy method");
    }

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
